package com.theobserver.theobserver;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.GetDataCallback;
import com.avos.avoscloud.SaveCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class UserHeadModifyActivity extends AppCompatActivity implements OnClickListener {
    private ImageView ivHead;//头像显示
    private Button btnTakephoto;//拍照
    private Button btnPhotos;//相册
    private Bitmap head;//头像Bitmap
    private static String path = Environment.getExternalStorageDirectory().toString()+File.separator;//sd路径
    private static final String TAG = "UserHeadModifyActivity";
    private static final int REQUEST_CODE = 0x11;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userheadmodify);

        TextView tv = (TextView) findViewById(R.id.textView_userheadmodify_return);//返回按钮
        tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               UserHeadModifyActivity.this.finish();
            }
        });


        initView();


        if(shouldAskPermission()) {
            String[] permissions = {"android.permission.WRITE_EXTERNAL_STORAGE"};
            //String[] permissions2 = {"android.permission.CAMERA"};
            ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE); // without sdk version check
            //ActivityCompat.requestPermissions(this, permissions2, REQUEST_CODE);
        }



    }

    private boolean shouldAskPermission(){

        return(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1);

    }





    private void initView() {
        //初始化控件
        btnPhotos = (Button) findViewById(R.id.btn_userheadmodify_photos);
        btnTakephoto = (Button) findViewById(R.id.btn_userheadmodify_takephoto);
        btnPhotos.setOnClickListener(this);
        btnTakephoto.setOnClickListener(this);
        ivHead = (ImageView) findViewById(R.id.iv_head);



        if(AVUser.getCurrentUser() == null)
        {
            Toast.makeText(UserHeadModifyActivity.this, "NULL", Toast.LENGTH_SHORT);
        }

        AVFile cur_user_head = AVUser.getCurrentUser().getAVFile("user_head");

        if(cur_user_head == null)
        {
            ivHead.setImageResource(R.drawable.logo);
        }
        else {
            cur_user_head.getDataInBackground(new GetDataCallback() {
                @Override
                public void done(byte[] bytes, AVException e) {
                    if (bytes != null) {
                        ivHead.setImageBitmap(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
                    } else {
                        ivHead.setImageResource(R.drawable.logo);
                    }
                }
            });
        }


        /*
        Bitmap bt = BitmapFactory.decodeFile(path + "head.jpeg");//从Sd中找头像，转换成Bitmap
        if(bt!=null){
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);//转换成drawable
            ivHead.setImageDrawable(drawable);
        }
        else{
            //AVFile file = null;
            AVFile file = AVUser.getCurrentUser().getAVFile("user_head");
            file.getDataInBackground(new GetDataCallback() {
                @Override
                public void done(byte[] bytes, AVException e) {
                    if (e == null) {
                        // bytes 就是文件的数据流
                        head = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        setPicToView(head);
                        ivHead.setImageBitmap(head);
                    } else {
                        Toast.makeText(UserHeadModifyActivity.this, "头像同步失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
            */
            /**
             *  如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
             *
             */

            //setPicToView(head);//保存在SD卡中
            //ivHead.setImageBitmap(head);//用ImageView显示出来
            //Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
        //}



    }


    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_userheadmodify_photos://从相册里面取照片
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
                break;
            case R.id.btn_userheadmodify_takephoto://调用相机拍照

                //if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1)
                //{
                /*
                    if(ContextCompat.checkSelfPermission(UserHeadModifyActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                    {
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 110);
                    }
                    else
                    {
                        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                                "head.jpeg")));
                        startActivityForResult(intent2, 2);//采用ForResult打开

                    }
                */
                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        "head.jpeg")));
                startActivityForResult(intent2, 2);//采用ForResult打开
                //}


                break;
            default:
                break;
        }
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());//裁剪图片
                }

                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory()
                            + "/head.jpeg");
                    cropPhoto(Uri.fromFile(temp));//裁剪图片
                }

                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if(head!=null){
                        final AVFile file = new AVFile("head.jpeg",Bitmap2Bytes(head));
                        file.saveInBackground(new SaveCallback() {
                            @Override
                            public void done(AVException e) {
                                if (e == null){
                                    Toast.makeText(UserHeadModifyActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                                    String Url = file.getUrl();
                                    AVUser.getCurrentUser().put("user_head", file);
                                    AVUser.getCurrentUser().saveInBackground(new SaveCallback() {
                                        @Override
                                        public void done(AVException e) {
                                            if(e != null)
                                            {
                                                //Toast.makeText(XiugaitouxiangActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                                                Log.d("MMMMM", e.toString());
                                            }
                                        }
                                    });
                                    //Toast.makeText(UserHeadModifyActivity.this, Url, Toast.LENGTH_SHORT).show();
                                    Log.d(TAG, file.getUrl());//返回一个唯一的 Url 地址



                                }
                                else {
                                    Toast.makeText(UserHeadModifyActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                                }

                            }
                        });
                        /**
                         * 上传服务器代码
                         */
                        //setPicToView(head);//保存在SD卡中
                        ivHead.setImageBitmap(head);//用ImageView显示出来
                    }
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 调用系统的裁剪
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }
    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        //path = Environment.getExternalStorageDirectory().toString()+File.separator;
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName =path + "head1.jpeg";//图片名字
        try {
            File f1 = new File(fileName);
            f1.createNewFile();
            b = new FileOutputStream(f1);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    public static byte[] Bitmap2Bytes(Bitmap bm){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }


    @Override

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // save file
                //Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                //intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                //        "head.jpeg")));
                //startActivityForResult(intent2, 2);//采用ForResult打开
            } else {
                Toast.makeText(getApplicationContext(), "PERMISSION_DENIED", Toast.LENGTH_SHORT).show();
            }
        }
    }



}